package com.chmingx.boot.converter;

import com.chmingx.boot.bean.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class DiyMessageConverter implements HttpMessageConverter<Person> {
    // 能否读取RequestBody中传过来的自定义数据类型 比如controller的参数中有 @RequestBody Person person
    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return false;
    }

    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return aClass.isAssignableFrom(Person.class); // 方法返回值类型时Person类型，就能写
    }

    /**
     * 服务器要统计所有MessageConverter都能处理那些媒体类型
     *
     * 我们自定义的是 application/x-diy
     * @return
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/x-diy");
    }

    @Override
    public Person read(Class<? extends Person> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    /**
     * 自定义协议数据的写出
     * @param person
     * @param mediaType
     * @param httpOutputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    public void write(Person person, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String data = person.getName() + ";" + person.getAge() + ";" + person.getBirth();

        // 写出去
        OutputStream body = httpOutputMessage.getBody();
        body.write(data.getBytes());
    }
}
